#!/usr/bin/env node

import { spawn } from 'child_process';
import { watch } from 'chokidar';
import path from 'path';
import { fileURLToPath } from 'url';
import process from 'process';
import { findMonorepoRoot } from '@mj-pro/node-utils';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 使用 findMonorepoRoot 获取大仓根目录
const monorepoRoot = findMonorepoRoot(__dirname);

// 监听路径
const watchPaths = [
  path.join(__dirname, '../src'),
  path.join(monorepoRoot, 'packages'),
];

// 启动进程
let nodeProcess = null;
let isRestarting = false;

function startServer() {
  if (isRestarting) {
    return;
  }

  if (nodeProcess) {
    console.warn('🔄 重启服务...');
    isRestarting = true;
    nodeProcess.kill('SIGTERM');

    // 等待进程完全关闭
    setTimeout(() => {
      isRestarting = false;
      startNodeProcess();
    }, 1000);
  } else {
    startNodeProcess();
  }
}

function startNodeProcess() {
  // 先运行unbuild stub生成文件，然后启动服务器
  const apiDir = path.join(__dirname, '..');
  const stubProcess = spawn('pnpm', ['unbuild', '--stub'], {
    cwd: apiDir,
    stdio: 'pipe',
    shell: true,
  });

  stubProcess.on('exit', (code) => {
    if (code !== 0) {
      console.error(`❌ Stub生成失败，代码: ${code}`);
      return;
    }

    // Stub生成成功后，启动服务器
    console.warn('✅ Stub文件生成完成，启动服务器...');
    nodeProcess = spawn('node', ['dist/index.mjs'], {
      cwd: apiDir,
      stdio: 'inherit',
      shell: true,
    });

    nodeProcess.on('exit', (code) => {
      if (code !== 0 && !isRestarting) {
        console.error(`❌ 服务退出，代码: ${code}`);
      }
    });

    nodeProcess.on('error', (error) => {
      if (!isRestarting) {
        console.error('❌ 启动服务失败:', error.message);
      }
    });
  });

  stubProcess.on('error', (error) => {
    console.error('❌ Stub生成失败:', error.message);
  });
}

// 设置文件监听
const watcher = watch(watchPaths, {
  ignored: [
    '**/node_modules/**',
    '**/dist/**',
    '**/*.test.ts',
    '**/*.spec.ts',
    '**/.turbo/**',
    '**/coverage/**',
  ],
  persistent: true,
  ignoreInitial: true,
  // 防抖，避免频繁重启
  awaitWriteFinish: {
    stabilityThreshold: 300,
    pollInterval: 100,
  },
});

watcher.on('change', (filePath) => {
  console.warn(`📝 文件变化: ${path.relative(__dirname, filePath)}`);
  startServer();
});

watcher.on('add', (filePath) => {
  console.warn(`➕ 新增文件: ${path.relative(__dirname, filePath)}`);
  startServer();
});

watcher.on('unlink', (filePath) => {
  console.warn(`🗑️ 删除文件: ${path.relative(__dirname, filePath)}`);
  startServer();
});

console.warn('🚀 启动unbuild开发服务器（高级模式）...');
console.warn(
  `👀 监听路径: ${watchPaths.map((p) => path.relative(__dirname, p)).join(', ')}`,
);
console.warn('💡 使用 Ctrl+C 停止服务');

// 初始启动
startServer();

// 优雅关闭
process.on('SIGINT', () => {
  console.warn('\n🛑 正在关闭开发服务器...');
  if (nodeProcess) {
    nodeProcess.kill('SIGTERM');
  }
  watcher.close();
  process.exit(0);
});

process.on('SIGTERM', () => {
  console.warn('\n🛑 正在关闭开发服务器...');
  if (nodeProcess) {
    nodeProcess.kill('SIGTERM');
  }
  watcher.close();
  process.exit(0);
});
